package com.tinyideatech.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tinyideatech.framework.utils.ShiroUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MetaObjectHandlerConfig implements  MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = getFieldValByName("createTime", metaObject);
        Object createBy = getFieldValByName("createBy", metaObject);
        String username = ShiroUtils.getUsername();

        if (createTime == null) {
            setFieldValByName("createTime", new Date(System.currentTimeMillis()), metaObject);
        }
        if (createBy == null && username != null) {
            setFieldValByName("createBy", username, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = getFieldValByName("updateTime", metaObject);
        Object updateBy = getFieldValByName("updateBy", metaObject);
        String username = ShiroUtils.getUsername();

        if (updateTime == null) {
            setFieldValByName("updateTime", new Date(System.currentTimeMillis()), metaObject);
        }
        if (updateBy == null && username != null) {
            setFieldValByName("updateBy", username, metaObject);
        }
    }

}
